import React, { useState } from "react";
import { createPortal } from "react-dom";
import Scrollbars from "react-custom-scrollbars";
import {
  DndContext,
  DragOverlay,
  defaultDropAnimation,
  MouseSensor,
  useSensor,
  useSensors,
  MeasuringStrategy,
} from "@dnd-kit/core";
import { restrictToWindowEdges } from "@dnd-kit/modifiers";
import DndFromCtx, { FunFormElement, genSchema } from "./core";
import WidgetCategories, { DraggableItem } from "./categories";
import WidgetConfig from "./configuration";
import MainRender from "./main";
import DragItem from "./main/card/dragItem";
import styles from "./index.module.less";

const FunForm = () => {
  const [instance, updateInstance] = useState<FunFormSchema>(genSchema());
  const [activedWidget, setActivedWidget] = useState<
    FunFormWidget | undefined
  >();
  const [activedElement, setActivedElement] =
    useState<ActivedElemnetType<any>>();

  const [activedWidgetCategory, setActivedWidgetCategory] =
    useState<WidgetCategory>();

  const mouseSensor = useSensor(MouseSensor, {
    activationConstraint: {
      distance: 15,
    },
  });

  const sensors = useSensors(mouseSensor);

  return (
    <Scrollbars autoHide>
      <DndFromCtx.Provider
        value={{
          activedWidget,
          setActivedWidget,
          instance,
          updateInstance,
          activedWidgetCategory,
          setActivedWidgetCategory,
          activedElement,
          setActivedElement,
        }}
      >
        <DndContext
          sensors={sensors}
          measuring={{
            droppable: {
              strategy: MeasuringStrategy.Always,
            },
          }}
        >
          <div className={styles.FunFormDesign}>
            <div className={styles.cagetroies}>
              <WidgetCategories />
            </div>
            <div className={styles.container}>
              <MainRender />
            </div>
            <div className={styles.config}>
              <WidgetConfig />
            </div>
          </div>
          {createPortal(
            <DragOverlay
              modifiers={[restrictToWindowEdges]}
              dropAnimation={{
                ...defaultDropAnimation,
                dragSourceOpacity: 0.5,
              }}
              style={{
                width: "auto",
              }}
            >
              {activedWidgetCategory && (
                <DraggableItem isOverLayer {...activedWidgetCategory} />
              )}
              {activedWidget &&
                activedWidget.type === FunFormElement.Widget && (
                  <DragItem
                    widget={activedWidget as FunFormWidget}
                    mode="horizontal"
                    labelWidth={70}
                    isOverLay
                  ></DragItem>
                )}
            </DragOverlay>,
            document.body
          )}
        </DndContext>
      </DndFromCtx.Provider>
    </Scrollbars>
  );
};

export default FunForm;
